package com.BaoHua.demo.threadDemo;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;


@NotThreadSafe
public class CountExample {

	private static int threadTotal = 200;
	private static int clientTotal = 5000;
	
	//在线程竞争很激烈的时候，技术用AtomicLong好一点
	public static AtomicInteger count = new AtomicInteger();
	
	public static LongAdder count2 = new LongAdder();
	
//	private static List<Integer> list = Collections.synchronizedList(new ArrayList());
	
	public static void main(String[] args) throws Exception {
		ExecutorService exec = Executors.newCachedThreadPool();
		final Semaphore semaphore = new Semaphore(threadTotal);
		final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
		for (int index = 0; index < clientTotal; index++) {
			exec.execute(() ->{
				try {
					semaphore.acquire();
					add();
					semaphore.release();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				countDownLatch.countDown();
			});
		}
		countDownLatch.await();
		//关闭线程池
		exec.shutdown();
		//System.out.println(count.get());
		System.out.println(count2);
	}
	
	private static void add() {
		//count.incrementAndGet();
		count2.increment();
	}
}
